package com.um.jdy.tcp.sdk;

import cn.hutool.core.date.DateUtil;
import cn.hutool.core.util.StrUtil;
import com.um.jdy.common.device.entity.po.Pile;
import com.um.jdy.common.device.enums.DeviceEnum;
import com.um.jdy.common.device.service.OnlineLogService;
import com.um.jdy.common.device.service.PileService;
import com.um.jdy.rpc.notify.RpcEBDeviceNotifyService;
import com.um.jdy.tcp.cmd.CommandReceiver;
import com.um.jdy.tcp.cmd.SDKCommand;
import com.um.jdy.tcp.event.AppEvent;
import lombok.extern.slf4j.Slf4j;
import org.apache.dubbo.config.annotation.DubboReference;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.ApplicationContext;
import org.springframework.context.ApplicationEvent;
import org.springframework.scheduling.annotation.Async;
import org.springframework.stereotype.Component;

import java.util.Date;

/**
 * @author 邓南辉
 * 日期 2023/8/28
 * 版权所有 广州优匠科技有限公司
 */
@Slf4j
@Component
public class CommandReceiverImpl implements CommandReceiver {

    @Autowired
    ApplicationContext applicationContext;

    @Autowired
    PileService pileService;

    @Autowired
    OnlineLogService onlineLogService;

    @DubboReference
    RpcEBDeviceNotifyService rpcEBDeviceNotifyService;

    @Async
    @Override
    public void receiver(String imei, SDKCommand command, Date time) {
        //log.info("收到指令：{},{}", imei, JSONUtil.toJSONString(command));
        ApplicationEvent event = new AppEvent<>(this, imei, time.getTime(), command);
        applicationContext.publishEvent(event);

        //只要有通讯，就更新心跳时间
//        try {
//            Pile pile = pileService.getRow("imei", imei);
//            if (pile != null) {
//                Pile updatePile = new Pile();
//                updatePile.setDevicePileId(pile.getDevicePileId());
//                updatePile.setDeviceStatus(DeviceEnum.DeviceStatus.Online.name());
//                updatePile.setHeartTime(time);
//                pileService.updateRow(updatePile);
//            }
//        } catch (Exception ex) {
//            log.error("", ex);
//        }
    }

    @Async
    @Override
    public void offline(String imei) {
        if (StrUtil.isEmpty(imei)) return;

        Pile pile = pileService.getRow("imei", imei);
        if (pile == null)
            return;

        Pile updatePile = new Pile();
        updatePile.setDevicePileId(pile.getDevicePileId());
        updatePile.setDeviceStatus(DeviceEnum.DeviceStatus.Offline.name());
        updatePile.setLastOfflineTime(DateUtil.date());
        pileService.updateRow(updatePile);

        onlineLogService.addOffline(pile.getCode(), pile.getName());

        rpcEBDeviceNotifyService.reqDeviceOffline(imei);

    }
}
